
package ru.samgtu.wst.util.swing;

import java.io.OutputStream;
import java.io.IOException;

import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import javax.swing.text.BadLocationException;


public class DocumentOutputStream extends OutputStream {

	PlainDocument _doc = new PlainDocument();
	private int _max;

	/** Creates a new instance of DocumentOutputStream */
	public DocumentOutputStream() {
		this(Integer.MAX_VALUE);
	}

	public DocumentOutputStream(int max) {
		_max = max;
	}

	public Document getDocument() {
		return _doc;
	}

	private void makeSpace(int count) {
		int length = _doc.getLength();
		if (length + count < _max) {
			return;
		}
		try {
			if (count > _max) {
				_doc.remove(0, length);
			} else {
				int min = length + count - _max;
				String remove = _doc.getText(min, Math.min(500, length - min));
				int cr = remove.indexOf("\n");
				if (cr < 0) {
					min = min + remove.length();
				} else {
					min = Math.min(min + cr + 1, length);
				}
				_doc.remove(0, min);
			}
		} catch (BadLocationException ble) {
			System.err.println("BLE! " + ble);
		}
	}

	@Override
	public void write(int b) throws IOException {
		try {
			makeSpace(1);
			_doc.insertString(_doc.getLength(), new String(
					new byte[] { (byte) (b & 0xFF) }, "ISO-8859-1"), null);
		} catch (BadLocationException ble) {
			throw new IOException(ble.getMessage());
		}
	}

	@Override
	public void write(byte[] buff) throws IOException {
		write(buff, 0, buff.length);
	}

	@Override
	public void write(byte[] buff, int off, int length) throws IOException {
		try {
			makeSpace(length);
			_doc.insertString(_doc.getLength(), new String(buff, off, length,
					"ISO-8859-1"), null);
		} catch (BadLocationException ble) {
			throw new IOException(ble.getMessage());
		}
	}

}
